/*
 * ds3231.c
 *
 *  Created on: May 22, 2021
 *      Author: kirk_
 */

#include "ds3231.h"

extern I2C_HandleTypeDef hi2c2;
extern _calendar_part calendar;//声明时钟结构体
void DS3231_Init(void)	//初始化
{

}

void DS3231_IIC_Write(uint8_t addr,uint8_t data)	//写数据
{
	while(HAL_OK != HAL_I2C_Mem_Write(&hi2c2, DS3231_Write_Address, addr, I2C_MEMADD_SIZE_8BIT, &data, 1, 0x1FFFF))
		HAL_Delay(1);
}

uint8_t DS3231_IIC_Read(uint8_t addr)	//读数据
{
	uint8_t data_s;
	while(HAL_OK != HAL_I2C_Mem_Read(&hi2c2, DS3231_Write_Address, addr, I2C_MEMADD_SIZE_8BIT, &data_s, 1, 0x1FFFF))
		HAL_Delay(1);
	return data_s;
}

void SetAlarmclock(uint8_t ahour,uint8_t amin,uint8_t asec)//设置闹钟
{
	uint8_t d;
	d = BIN_BCD(ahour);
	DS3231_IIC_Write(DS3231_AL1HOUR_REG,d);
	d = BIN_BCD(amin);
	DS3231_IIC_Write(DS3231_AL1MIN_REG,d);
	d = BIN_BCD(asec);
	DS3231_IIC_Write(DS3231_AL1SEC_REG,d);
	DS3231_IIC_Write(DS3231_AL1WDAY_REG,0x80);
}

void Alarmclock1_cmd(uint8_t mode)//mode = 1 / 0  闹钟使能
{
	DS3231_IIC_Write(DS3231_CONTROL_REG,0x1C|mode);
}

uint8_t Alarmclock1state(void)	//读闹钟响应标志
{
	uint8_t A1F;
	A1F=DS3231_IIC_Read(DS3231_STATUS_REG)&0x01;
	return A1F;
}

void Alarmclock1_close(void)	//关闭闹钟并清除标志位
{
	Alarmclock1_cmd(0);
	DS3231_IIC_Write(DS3231_STATUS_REG,0x00);
}

void ModifyTime(uint8_t year,uint8_t month,uint8_t day,uint8_t hour,uint8_t min,uint8_t sec)//修改时间
{
	uint8_t temp;
	temp = BIN_BCD(year);
	DS3231_IIC_Write(DS3231_YEAR_REG,temp);
	temp = BIN_BCD(month);
	DS3231_IIC_Write(DS3231_MONTH_REG,temp);
	temp = BIN_BCD(day);
	DS3231_IIC_Write(DS3231_MDAY_REG,temp);
	temp = BIN_BCD(hour);
	DS3231_IIC_Write(DS3231_HOUR_REG,temp);
	temp = BIN_BCD(min);
	DS3231_IIC_Write(DS3231_MIN_REG,temp);
	temp = BIN_BCD(sec);
	DS3231_IIC_Write(DS3231_SEC_REG,temp);
}

void get_time(void)//获取时间
{
	calendar.year = DS3231_IIC_Read(DS3231_YEAR_REG);
	calendar.year = BCD_BIN(calendar.year);

	calendar.month = DS3231_IIC_Read(DS3231_MONTH_REG);
	calendar.month = BCD_BIN(calendar.month);

	calendar.day = DS3231_IIC_Read(DS3231_MDAY_REG);
	calendar.day = BCD_BIN(calendar.day);

	calendar.hour = DS3231_IIC_Read(DS3231_HOUR_REG);
	calendar.hour &= 0x3f;
	calendar.hour = BCD_BIN(calendar.hour);

	calendar.min = DS3231_IIC_Read(DS3231_MIN_REG);
	calendar.min = BCD_BIN(calendar.min);

	calendar.sec = DS3231_IIC_Read(DS3231_SEC_REG);
	calendar.sec = BCD_BIN(calendar.sec);
}

uint8_t BCD_BIN(uint8_t val)//BCD码转换为二进制
{
	uint8_t temp;
	temp=val&0x0f;
	val>>=4;
	val&=0x0f;
	val*=10;
	temp+=val;
	return temp;
}

uint8_t BIN_BCD(uint8_t val)//二进制转换为BCD码
{
	uint8_t i,j,k;
	i=val/10;
	j=val%10;
	k=j+(i<<4);
	return k;
}


